package com.dyz.leetcode;

import java.util.ArrayDeque;
import java.util.Deque;

public class DecodeString394 {
    public static void main(String[] args) {
        new DecodeString394().decodeString("3[a2[bc]]");
    }
    public String decodeString(String s) {
        Deque<Integer> numStack = new ArrayDeque<>();
        Deque<String> strStck = new ArrayDeque<>();
        StringBuilder tail = new StringBuilder();
        int n = s.length();
        for (int i = 0; i<n; i++){
            char c = s.charAt(i);
            if (Character.isDigit(c)){
                int num=c-'0';
                //下一位是否为数字
                while (i+1<n && Character.isDigit(s.charAt(i+1))){
                    num = num*10+(s.charAt(i+1)-'0');
                    i++;
                }
                numStack.push(num);
            }else if(c=='['){
                strStck.push(tail.toString());
                //tail清空
                tail = new StringBuilder();
            }else if(c==']'){
                StringBuilder tmp = new StringBuilder(strStck.pop());
                int repeat = numStack.poll();
                for(int j=0; j<repeat; j++){
                    tmp.append(tail);
                }
                tail = tmp;
            }else {
                tail.append(c);
            }
        }
        return tail.toString();
    }
}
